﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace THProjectMain
{
    public partial class FrmMain : Form
    {
        //创建通信库类对象
        ModbusRTULib.ModbusRTU modbusRTU = new ModbusRTULib.ModbusRTU();

        public FrmMain()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            //绑定波特率下拉列表
            string[] allBaudRate = new string[] {
                "2400",
                "4800",
                "9600",
                "19200",
                "38400",
                "57600",
                "115200"
            };
            this.cmb_BaudRate.Items.AddRange(allBaudRate);
            this.cmb_BaudRate.SelectedIndex = 2;

            //电脑当前可用端口号
            this.cmb_PortName.DataSource = SerialPort.GetPortNames();

            //定时器设置
            this.timer_Read.Interval = 1000;
        }

        #region 串口连接状态属性设置
        private bool _isConnected = false;
        public bool IsConnected 
        {
            get { return _isConnected; }
            set {  
                _isConnected = value; //保存当前的状态
                this.btn_OpenAndClose.Text = value ? "断开连接" : "连接设备";
                this.btn_OpenAndClose.ForeColor = Color.White;
                if (value) //如果打开连接显示的是断开连接
                {
                    this.btn_OpenAndClose.BackColor = Color.Red;
                    this.lblStatus.ForeColor = Color.Green;
                    //this.btn_OpenAndClose.ForeColor = Color.White;
                }
                else
                {
                    this.btn_OpenAndClose.BackColor = Color.Green;
                    this.lblStatus.ForeColor= Color.Red;
                    //this.btn_OpenAndClose.ForeColor = Color.White;
                }
            }
        }
        #endregion

        #region 打开和关闭连接
        private void btn_OpenAndClose_Click(object sender, EventArgs e)
        {
            if (!IsConnected)
            {
                try
                {
                    modbusRTU.Connect(this.cmb_PortName.Text, Convert.ToInt32(this.cmb_BaudRate.Text));
                    IsConnected = true;
                    this.timer_Read.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误提示");
                }
            }
            else
            {
                this.timer_Read.Stop();//首先要停止定时器的读取
                modbusRTU.Disconnect();
                IsConnected = false;
            }
        }
        #endregion

        #region 定时循环读取寄存器数据
        private void timer_Read_Tick(object sender, EventArgs e)
        {
            //读取数据（2个寄存器，起始地址0000H）
            byte[] result = modbusRTU.ReadHoldingRegister(Convert.ToByte(this.nud_SlaveId.Value), 0, 2);

            //解析并显示数据
            if (result != null && result.Length == 4)
            {
                int humldity = result[0] * 256 + result[1];
                int temperature = result[2] * 256 + result[3];
                //显示数字
                this.lbl_Humidity.Text = (humldity * 0.1).ToString();
                this.lbl_Temp.Text = (temperature * 0.1).ToString();

                //显示图形
                this.thMeter_H.SerHTValue = humldity * 0.1;
                this.thMeter_T.SerHTValue = temperature * 0.1;
            }
        }
        #endregion

        //窗体关闭之前
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //关闭定时器
            this.timer_Read.Stop();
        }
    }
}
